package com.flyduck.manager;

import com.alibaba.fastjson.JSON;
import com.flyduck.constant.SysConstant;
import com.flyduck.entity.SysMenu;
import com.flyduck.mapper.SysMenuMapper;
import com.flyduck.vo.UserPermRespVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * NavManager
 * </p>
 *
 * @author flyduck
 * @since 2024-05-31
 */
@Slf4j
@Component
public class NavManager {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    public List<UserPermRespVO.NavDTO> getNavTreeByUserId(Long userId) {
        List<SysMenu> sysMenuList = sysMenuMapper.getMenuListByUserId(userId);
        //转实体
        List<UserPermRespVO.NavDTO> navDTOList = convertToNavDTOList(sysMenuList);

        //转树状结构
        List<UserPermRespVO.NavDTO> navDTOTree = buildTreeMenu(navDTOList);
        return navDTOTree;
    }

    private List<UserPermRespVO.NavDTO> convertToNavDTOList(List<SysMenu> sysMenuList) {
        return sysMenuList.stream()
                    .map(sysMenu -> {
                        UserPermRespVO.NavDTO navDTO = new UserPermRespVO.NavDTO();
                        navDTO.setId(sysMenu.getId());
                        navDTO.setParentId(sysMenu.getParentId());
                        navDTO.setType(sysMenu.getType());
                        navDTO.setName(sysMenu.getPerms());
                        navDTO.setTitle(sysMenu.getName());
                        navDTO.setIcon(sysMenu.getIcon());
                        navDTO.setPath(sysMenu.getPath());
                        navDTO.setComponent(sysMenu.getComponent());

                        return navDTO;
                    }).collect(Collectors.toList());
    }

    private List<UserPermRespVO.NavDTO> buildTreeMenu(List<UserPermRespVO.NavDTO> navDTOList) {
        List<UserPermRespVO.NavDTO> treeMenu = new ArrayList<>();

        // 各自找到自己的孩子（目录的孩子是菜单，菜单的孩子是按钮），如果是目录放到treeMenu里面
        for (UserPermRespVO.NavDTO directory : navDTOList) {
            for (UserPermRespVO.NavDTO menu : navDTOList) {
                if(menu.getParentId().equals(directory.getId())){
                    directory.getChildren().add(menu);
                }
            }
            if(SysConstant.MenuType.DIRECTORY.getCode() == directory.getType()){
                treeMenu.add(directory);
            }
        }
        log.info("菜单树:\n", JSON.toJSONString(treeMenu, true));
        return treeMenu;
    }
}
